from django.db import models
from django.contrib.auth.models import User
from categories.models import Category

class Book(models.Model):
    STATUS_CHOICES = (
        ('available', '可借阅'),
        ('borrowed', '已借出'),
        ('reserved', '已预约'),
        ('damaged', '损坏'),
        ('lost', '丢失'),
    )

    title = models.CharField(max_length=200, verbose_name='书名')
    author = models.CharField(max_length=100, verbose_name='作者')
    isbn = models.CharField(max_length=13, unique=True, verbose_name='ISBN')
    publisher = models.CharField(max_length=100, verbose_name='出版社')
    publish_date = models.DateField(verbose_name='出版日期')
    category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='books', verbose_name='分类')
    description = models.TextField(blank=True, verbose_name='描述')
    cover_image = models.ImageField(upload_to='book_covers/', blank=True, null=True, verbose_name='封面图片')
    page_count = models.PositiveIntegerField(default=0, verbose_name='页数')
    language = models.CharField(max_length=50, default='中文', verbose_name='语言')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='available', verbose_name='状态')
    location = models.CharField(max_length=100, blank=True, verbose_name='位置')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '图书'
        db_table = 'api_books'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.title} - {self.author}"

    def is_available(self):
        """检查图书是否可借阅"""
        return self.status == 'available'

    def get_borrowing_history(self):
        """获取图书的借阅历史"""
        return Borrowing.objects.filter(book=self).order_by('-borrow_date')

    def get_current_borrowing(self):
        """获取图书当前借阅记录（如果有）"""
        try:
            return Borrowing.objects.get(book=self, return_date__isnull=True)
        except Borrowing.DoesNotExist:
            return None

